package com.ruoyi.gpt.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.gpt.constants.GptGoodsType;
import com.ruoyi.gpt.constants.PayStatusConstants;
import com.ruoyi.gpt.domain.GptUser;
import com.ruoyi.gpt.domain.bo.GptUserBo;
import com.ruoyi.gpt.domain.vo.GptUserVo;
import com.ruoyi.gpt.mapper.GptUserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.gpt.domain.bo.GptOrderBo;
import com.ruoyi.gpt.domain.vo.GptOrderVo;
import com.ruoyi.gpt.domain.GptOrder;
import com.ruoyi.gpt.mapper.GptOrderMapper;
import com.ruoyi.gpt.service.IGptOrderService;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * Gpt订单列表Service业务层处理
 *
 * @author ztx
 * @date 2023-04-10
 */
@RequiredArgsConstructor
@Service
public class GptOrderServiceImpl implements IGptOrderService {

    private final GptOrderMapper baseMapper;

    private final GptUserMapper gptUserMapper;

    /**
     * 查询Gpt订单列表
     */
    @Override
    public GptOrderVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询Gpt订单列表列表
     */
    @Override
    public TableDataInfo<GptOrderVo> queryPageList(GptOrderBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<GptOrder> lqw = buildQueryWrapper(bo);
        Page<GptOrderVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询Gpt订单列表列表
     */
    @Override
    public List<GptOrderVo> queryList(GptOrderBo bo) {
        LambdaQueryWrapper<GptOrder> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<GptOrder> buildQueryWrapper(GptOrderBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<GptOrder> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, GptOrder::getUserId, bo.getUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getAppid()), GptOrder::getAppid, bo.getAppid());
        lqw.eq(StringUtils.isNotBlank(bo.getIsPay()), GptOrder::getIsPay, bo.getIsPay());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), GptOrder::getStatus, bo.getStatus());
        lqw.eq(bo.getSalesPrice() != null, GptOrder::getSalesPrice, bo.getSalesPrice());
        lqw.eq(bo.getPaymentPrice() != null, GptOrder::getPaymentPrice, bo.getPaymentPrice());
        lqw.eq(bo.getPaymentTime() != null, GptOrder::getPaymentTime, bo.getPaymentTime());
        lqw.eq(StringUtils.isNotBlank(bo.getUserMessage()), GptOrder::getUserMessage, bo.getUserMessage());
        lqw.like(StringUtils.isNotBlank(bo.getGoodsName()), GptOrder::getGoodsName, bo.getGoodsName());
        return lqw;
    }

    /**
     * 新增Gpt订单列表
     */
    @Override
    public Boolean insertByBo(GptOrderBo bo) {
        GptOrder add = BeanUtil.toBean(bo, GptOrder.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改Gpt订单列表
     */
    @Override
    public Boolean updateByBo(GptOrderBo bo) {
        GptOrder update = BeanUtil.toBean(bo, GptOrder.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(GptOrder entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除Gpt订单列表
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void changeOrderStatus(GptOrderVo gptOrderVo) {
        //判断是未支付状态
        if(!PayStatusConstants.NO_PAY.equals(gptOrderVo.getStatus()) || !"0".equals(gptOrderVo.getIsPay())){
            return;
        }
        // 修改订单状态
        gptOrderVo.setStatus(PayStatusConstants.FINISH);
        gptOrderVo.setIsPay("1");
        baseMapper.updateById(BeanUtil.toBean(gptOrderVo, GptOrder.class));
        Long userId = gptOrderVo.getUserId();
        String goodsType = gptOrderVo.getGoodsType();
        if(GptGoodsType.count.equals(goodsType)){
            // 增加次数
            GptUserVo gptUserVo = gptUserMapper.selectVoById(userId);
            if(ObjectUtil.isNotNull(gptUserVo)){
                gptUserVo.setGptRemaining((int) (gptUserVo.getGptRemaining() + gptOrderVo.getGoodsValueCounts()));
                gptUserMapper.updateById(BeanUtil.toBean(gptUserVo, GptUser.class));
            }
        } else if (GptGoodsType.time.equals(goodsType)) {
            // 增加时间
            GptUserVo gptUserVo = gptUserMapper.selectVoById(userId);
            if(ObjectUtil.isNotNull(gptUserVo)){
                Date gptEndTime = gptUserVo.getGptEndTime();
                //判断是否过期是否未null，如果已过期或者未null,则从当前时间开始计算
                if(ObjectUtil.isNull(gptEndTime) || gptEndTime.getTime() < System.currentTimeMillis()){
                    gptEndTime = new Date();
                }
                //转为时间戳
                long gptEndTimeLong = gptEndTime.getTime();
                // 购买的时长是
                long goodsValueTimes = Long.parseLong(gptOrderVo.getGoodsValueTimes());
                // 总时间是
                long newTime = gptEndTimeLong + (goodsValueTimes *1000);
                //转为时间
                Date newDate = new Date(newTime);
                gptUserVo.setGptEndTime(newDate);
                gptUserMapper.updateById(BeanUtil.toBean(gptUserVo, GptUser.class));
            }
        }
    }
}
